inp = "E:\\马\\文件\\py_test\\text\\image\\IMG_0588 (1).jpg"  
oup = "E:\\马\\文件\\py_test\\text\\image\\split"  
# 分割方式(size/count)
mode = "count"
if mode == "size":
    # 分割尺寸
    splitHeight = 960//2
    splitWidth = 960//2
if mode == "count":
    # 分割数量
    splitNumHeight = 5
    splitNumWeight = 5
else:
    print("分割方式错误！")
    exit()

# 只需修改以上内容
# ---------------------
from PIL import Image

def split_image(image_path, output_path, x, y, width, height):
    with Image.open(image_path) as img:
        # 确保图片为 RGBA 模式（含透明度）
        img = img.convert("RGBA")
        # 裁剪指定区域（left, upper, right, lower）
        cropped = img.crop((x, y, x+width, y+height))
        cropped.save(output_path, "PNG", optimize=True)
        
# 打开输入文件
img = Image.open(inp)
# 创建输出文件夹
import os
if not os.path.exists(oup):
    os.makedirs(oup)

# 确定分割数量
imgHeight = img.size[1]
imgWidth = img.size[0]

if mode == "size":
    # 计算分割数量
    splitNumHeight = imgHeight // splitHeight
    splitNumWeight = imgWidth // splitWidth
if mode == "count":
    # 计算分割尺寸
    splitHeight = imgHeight // splitNumHeight
    splitWidth = imgWidth // splitNumWeight

existToDo = False
existToDoWhat = ""

# 循环分割并保存
for i in range(splitNumHeight):
    for j in range(splitNumWeight):
        # 计算分割区域
        x = j * splitWidth
        y = i * splitHeight
        thisOup = oup + "/" + f'{i*splitNumWeight+j+1:04d}' + ".png"
        while os.path.exists(thisOup):
            if existToDo:
                if existToDoWhat == "Y":
                    open(thisOup, 'w').close()
                    split_image(inp, thisOup, x, y, splitWidth, splitHeight)
                    break
                elif existToDoWhat == "N":
                    break
            w = input("文件已存在，是否覆盖？(Y/N/AY/AN)")
            if w == "Y" or w == "y":
                open(thisOup, 'w').close()
                split_image(inp, thisOup, x, y, splitWidth, splitHeight)
                break
            elif w == "N" or w == "n":
                break
            if w == "AY" or w == "ay":
                open(thisOup, 'w').close()
                split_image(inp, thisOup, x, y, splitWidth, splitHeight)
                existToDo = True
                existToDoWhat = "Y"
                break
            elif w == "AN" or w == "an":
                existToDo = True
                existToDoWhat = "N"
                break
            else:
                print("输入错误，请重新输入！")
        else:
            open(thisOup, 'w').close()
            split_image(inp, thisOup, x, y, splitWidth, splitHeight)